﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 作者：曾永佑
 * 版本：
 * 创建日期：2013-09-28
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */  
        
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web; 
using System.Web.Mvc;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System;

namespace SRF.UI.Html
{
    public static class SelectorExtensions
    {
        #region

        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
        public static MvcHtmlString SelectorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            string caption,
            IEnumerable<SelectListItem> selectList,
            bool readOnly = false)
        {
            StringBuilder htmlFormat = new StringBuilder();

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            htmlFormat.Append("<div id='select_{0}'>");
            htmlFormat.Append("<b>{1}：</b>");
            htmlFormat.Append("<div class='select_body'><div class='selected-tags'></div>");
            htmlFormat.Append("<select style='{2}'>{3}</select>");
            htmlFormat.Append("<input id='{0}' name='{0}' type='hidden' value='{4}'/>");
            htmlFormat.Append("</div></div>");

            string optionshtml = "<option>--" + caption + "--</option>";
            foreach (SelectListItem item in selectList)
            {
                optionshtml += string.Format("<option value='{0}'>{1}</option>", item.Value, item.Text);
            }
            string html = string.Format(htmlFormat.ToString(), metadata.PropertyName, metadata.DisplayName, readOnly ? "display:none" : "", optionshtml, metadata.Model == null ? "" : metadata.Model);

            string script = string.Format("<script type='text/javascript'>initSelector('select_Roles',{0}); </script>", readOnly.ToString().ToLower());
            html += script;

            return new MvcHtmlString(html);
        }

        #endregion
    }
}